package com.ForkJoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

/**
 *  分支算法 -> 工作窃取
 *  ForkJoin
 *
 * */
public class ForkJoinDemo {
    public static void main(String[] args) throws InterruptedException {
        testNoResultTask();
    }
    private static void testNoResultTask() throws InterruptedException{
        ForkJoinPool pool = new ForkJoinPool();
        pool.submit(new task1(1,2000));
        //线程阻塞，等待所有任务完成
        pool.awaitTermination(2, TimeUnit.SECONDS);
        pool.shutdown();
    }
}
//不带返回值
class task1 extends RecursiveAction{

    private static final long serialVersionUID = 1L;

    private static final int THRESHOLD = 9;

    private int start;

    private int end;

    public task1(int start, int end) {
        super();
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        //如果小于阈值，就不需要拆分
        if(end - start  < THRESHOLD) {
            for(int i=start;i<=end;i++) {
                System.out.println(Thread.currentThread().getName()+",i="+i);
            }
        }else {
            int middle = (start + end) / 2;
            //二分法
            task1 firstTask = new task1(start,middle);
            task1 secondTask = new task1(middle+1,end);
            invokeAll(firstTask,secondTask);//递归 压入线程


            System.out.println(firstTask.join()+"--," + secondTask.join());
        }
    }
}
